﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using DBCSCodePage;
using HtmlAgilityPack;

namespace NGA
{
    public partial class ThreadPage : PhoneApplicationPage
    {
        private string uri = string.Empty;
        private string title = string.Empty;
        
        private int curPage = 1;
        private int curViewState = 0;
        private bool isEnd = false;

        private ScrollViewerHandler viewHandler;

        public ThreadPage()
        {
            InitializeComponent();
            
            uri = string.Empty;
            title = string.Empty;

            curPage = 1;
            curViewState = 0;
            isEnd = false;
            viewHandler = new ScrollViewerHandler();

            DataContext = App.Board;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            IDictionary<string, string> query = this.NavigationContext.QueryString;
            if(query.ContainsKey("href"))
            {
                uri = query["href"];
            }
            ((ThreadModel)DataContext).Posts.Clear();
            HttpHandler contentRequest = new HttpHandler(uri, string.Empty, DBCSEncoding.GetDBCSEncoding("gb2312"), PraseThreadData);
            base.OnNavigatedTo(e);
        }

        private bool PraseThreadData(String result)
        {
            HtmlDocument html = new HtmlDocument();
            html.LoadHtml(result);

            title = html.GetElementbyId("postsubject").InnerText;
            title = title.Remove(0, 2);
            title = title.Remove(title.Length - 2, 2);
            Deployment.Current.Dispatcher.BeginInvoke( () => {Topic.Text = title;} );

            for (int i = 0; ; i++)
            {
                try
                {
                    int floor = (curPage - 1) * 20 + i;
                    string poster = "--------" + floor.ToString() + "楼";
                    string postContent = html.GetElementbyId("postcontent" + floor.ToString()).InnerText;

                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        ((ThreadModel)DataContext).Posts.Add(new PostInfo()
                        {
                            Poster = poster,
                            PostContent = postContent
                        });
                    });
                }
                catch (System.Exception ex)
                {
                    if (i < 20)
                    {
                        isEnd = true;
                    }
                    // END of thread
                    break;
                }
            }
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                loadProgress.Visibility = System.Windows.Visibility.Collapsed;
                viewHandler.ProcessViewer(ThreadContent, visualStateGroup_CurrentStateChanged);
            });

            return true;
        }

        /// <summary>
        /// 状态改变
        /// </summary>
        private void visualStateGroup_CurrentStateChanged(object sender, VisualStateChangedEventArgs e)
        {
            var visualState = e.NewState.Name;
            ScrollViewer view = viewHandler.scrollViewer;
            if (visualState == "NotScrolling")
            {
                var v1 = view.ExtentHeight;
                var v2 = view.VerticalOffset;
                if (view.ExtentHeight - view.VerticalOffset - view.ViewportHeight < 0.000001 && !isEnd)
                {
                    if (curViewState == 1)
                    {
                        loadProgress.Visibility = System.Windows.Visibility.Visible;
                        curPage++;
                        HttpHandler contentRequest = new HttpHandler(uri, "page=" + curPage.ToString(), DBCSEncoding.GetDBCSEncoding("gb2312"), PraseThreadData);
                    }
                    else
                    {
                        curViewState = 1;
                    }
                }
                else
                {
                    curViewState = 0;
                }
            }
        }
    }
}